package cn.scau.server.service.impl;

import cn.scau.server.dto.PositionPageDTO;
import cn.scau.server.mapper.DeptMapper;
import cn.scau.server.mapper.EmpMapper;
import cn.scau.server.mapper.EmpPosMapper;
import cn.scau.server.pojo.Dept;
import cn.scau.server.pojo.Emp;
import cn.scau.server.pojo.EmpPos;
import cn.scau.server.pojo.Position;
import cn.scau.server.mapper.PositionMapper;
import cn.scau.server.service.PositionService;
import cn.scau.server.vo.EmpPosDeptVO;
import cn.scau.server.vo.ResultVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 代码不跑我先跑
 * @since 2025-03-30
 */
@Service
public class PositionServiceImpl extends ServiceImpl<PositionMapper, Position> implements PositionService {
    @Autowired
    private PositionMapper positionMapper;

    @Autowired
    private EmpPosMapper empPosMapper;

    @Autowired
    private EmpMapper empMapper;

    @Autowired
    private DeptMapper deptMapper;

    //添加职位
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultVO addPosition(String name, String deptName){
        if (name == null || name.length() == 0) {
            return ResultVO.fail("职位名称不能为空");
        }
        if (deptName == null || deptName.length() == 0) {
            return ResultVO.fail("部门名称不能为空");
        }

        // 检查是否已经存在同名的职位
        QueryWrapper<Position> querySameWrapper = new QueryWrapper<>();
        querySameWrapper.eq("name", name);
        Position existingPosition = positionMapper.selectOne(querySameWrapper);
        if (existingPosition != null) {
            return ResultVO.fail("职位名称已存在");
        }

        // 根据部门名称查找部门 ID
        QueryWrapper<Dept> deptQueryWrapper = new QueryWrapper<>();
        deptQueryWrapper.eq("name", deptName);
        Dept dept = deptMapper.selectOne(deptQueryWrapper);
        if (dept == null) {
            return ResultVO.fail("部门不存在");
        }
        Integer deptId = dept.getId();

        //创建新职位
        Position position = new Position();
        position.setName(name);
        position.setDeptId(deptId);
        boolean success = positionMapper.insert(position) > 0;
        if (success) {
            return ResultVO.success("新增职位成功");
        } else {
            return ResultVO.fail("新增职位失败");
        }
    }

    //修改职位
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultVO editPosition(Integer positionId, String name){
        if (name == null || name.length() == 0) {
            return ResultVO.fail("职位名称不能为空");
        }

        // 检查是否已经存在同名的职位
        QueryWrapper<Position> querySameWrapper = new QueryWrapper<>();
        querySameWrapper.eq("name", name);
        Position existingPosition = positionMapper.selectOne(querySameWrapper);
        if (existingPosition != null) {
            return ResultVO.fail("职位名称已存在");
        }

        // 根据 id 查找职位
        Position position = positionMapper.selectById(positionId);
        if (position == null) {
            return ResultVO.fail("职位不存在");
        }

        // 更新职位名称
        position.setName(name);
        boolean success = positionMapper.updateById(position) > 0;
        if (success) {
            return ResultVO.success("修改职位成功",position);
        } else {
            return ResultVO.fail("修改职位失败");
        }
    }

    //删除职位
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultVO deletePosition(Integer positionId){
        // 根据 id 查找职位
        Position position = positionMapper.selectById(positionId);
        if (position == null) {
            return ResultVO.fail("职位不存在");
        }

        // 检查 EmpPos 表中是否有员工的职位编号是当前待删除的职位编号
        List<EmpPos> empPosList = empPosMapper.selectList(new QueryWrapper<EmpPos>().eq("position_id", positionId));
        if (!empPosList.isEmpty()) {
            return ResultVO.fail("该职位下存在员工，无法删除");
        }

        // 删除职位
        boolean success = positionMapper.deleteById(positionId) > 0;
        if (success) {
            return ResultVO.success("删除职位成功");
        } else {
            return ResultVO.fail("删除职位失败");
        }
    }

    //分页查询职位信息
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultVO<IPage<Position>> pagePosition(PositionPageDTO positionPageDTO) throws Exception{
        //获取分页大小，如果为 null，则使用默认值 10
        int pageSize = (positionPageDTO.getPageSize() != null) ? positionPageDTO.getPageSize() : 10;
        // 获取当前页码，如果为 null，则使用默认值 1
        int pageNum = (positionPageDTO.getPageNum() != null) ? positionPageDTO.getPageNum() : 1;
        IPage<Position> page=new Page<>(pageNum,pageSize);
        return ResultVO.success("查询成功",positionMapper.pagePosition(page,positionPageDTO));
    }

    //根据职位编号查找所有拥有该职位的员工信息
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultVO<List<EmpPosDeptVO>> getEmpsByPositionId(Integer positionId) {
        // 根据职位编号查找职位
        QueryWrapper<Position> positionQueryWrapper = new QueryWrapper<>();
        positionQueryWrapper.eq("id", positionId);
        Position position = positionMapper.selectOne(positionQueryWrapper);
        if (position == null) {
            return ResultVO.fail("职位不存在");
        }

        // 查询拥有该职位的所有员工
        QueryWrapper<EmpPos> empPosQueryWrapper = new QueryWrapper<>();
        empPosQueryWrapper.eq("position_id", positionId);
        List<EmpPos> empPosList = empPosMapper.selectList(empPosQueryWrapper);

        // 查询员工信息并封装到 EmpPosDeptVO
        List<EmpPosDeptVO> empPosDeptVOList = new ArrayList<>();
        for (EmpPos empPos : empPosList) {
            // 查询员工信息
            QueryWrapper<Emp> empQueryWrapper = new QueryWrapper<>();
            empQueryWrapper.eq("emp_id", empPos.getEmpId());
            empQueryWrapper.eq("is_deleted", 0);
            Emp emp = empMapper.selectOne(empQueryWrapper);

            // 如果员工不存在或已被逻辑删除，则跳过
            if (emp == null) {
                continue;
            }

            // 查询部门信息
            QueryWrapper<Dept> deptQueryWrapper = new QueryWrapper<>();
            deptQueryWrapper.eq("id", empPos.getDeptId());
            Dept dept = deptMapper.selectOne(deptQueryWrapper);

            if (emp != null && dept != null) {
                // 创建 EmpPosDeptVO 对象并添加到列表
                EmpPosDeptVO empPosDeptVO = new EmpPosDeptVO();
                empPosDeptVO.setEmpId(empPos.getEmpId());
                empPosDeptVO.setName(emp.getName());
                empPosDeptVO.setDeptId(dept.getId());
                empPosDeptVO.setDeptName(dept.getName());
                empPosDeptVO.setPositionId(empPos.getPositionId());
                empPosDeptVO.setPositionName(position.getName());
                empPosDeptVO.setIsLeader(empPos.getIsLeader());
                empPosDeptVO.setAge(emp.getAge());
                empPosDeptVOList.add(empPosDeptVO);
            }
        }
        return ResultVO.success("查询成功", empPosDeptVOList);
    }

    //根据部门名称查找所有职位
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultVO<List<String>> getPositionsByDeptName(String deptName) {
        // 根据部门名称查找部门
        QueryWrapper<Dept> deptQueryWrapper = new QueryWrapper<>();
        deptQueryWrapper.eq("name", deptName);
        Dept dept = deptMapper.selectOne(deptQueryWrapper);
        if (dept == null) {
            return ResultVO.fail("部门不存在");
        }

        // 根据部门ID在Position表中查找所有职位名称
        QueryWrapper<Position> positionQueryWrapper = new QueryWrapper<>();
        positionQueryWrapper.eq("dept_id", dept.getId());
        List<Position> positions = positionMapper.selectList(positionQueryWrapper);

        if (positions.isEmpty()) {
            return ResultVO.fail("该部门下没有职位");
        }

        // 提取职位名称列表
        List<String> positionNames = new ArrayList<>();
        for (Position position : positions) {
            positionNames.add(position.getName());
        }

        return ResultVO.success("查询成功", positionNames);
    }
}
